package glog

import (
	"fmt"
	"time"

	"gitee.com/mkwchecking/sr-core/log/ilog"
	"gitee.com/mkwchecking/sr-core/utils/style"
)

type Config struct {
	Level         ilog.Level    `json:"level"`         // log level
	TraceKey      string        `json:"traceKey"`      // get trace id from ctx
	SlowThreshold time.Duration `json:"slowThreshold"` // slow threshold (ms)
	Colorful      bool          `json:"colorful"`      // colorful
	CallSkip      int           `json:"callSkip"`      // call skip
}

func newMentionFormat() mentionFormat {
	return mentionFormat{
		info:      "%s\n[info ] ",
		warning:   "%s\n[warn ] ",
		err:       "%s\n[error] ",
		trace:     "%s [%.3fms] [rows:%v] %s",
		traceWarn: "%s %s [%.3fms] [rows:%v] %s",
		traceErr:  "%s %s [%.3fms] [rows:%v] %s",
	}
}

func newColorfulMentionFormat() mentionFormat {
	return mentionFormat{
		info:      style.Green("%s [info ] "),
		warning:   style.Blue("%s", true) + style.Magenta("[warn ] "),
		err:       style.Magenta("%s") + style.Red("[error] "),
		trace:     style.Green("%s ") + style.Yellow("[%.3fms]") + style.Blue(" [rows:%v]", true) + "%s",
		traceWarn: style.Green("%s ") + style.Yellow("%s ") + style.Red("[%.3fms]", true) + style.Yellow("[rows:%v]") + style.Magenta("%s"),
		traceErr:  style.Red("%s ", true) + style.Magenta("%s ", true) + style.Yellow("[%.3fms]") + style.Blue("[rows:%v]") + "%s",
	}
}

type mentionFormat struct {
	info      string
	warning   string
	trace     string
	err       string
	traceWarn string
	traceErr  string
}

func (m mentionFormat) infoFormat(callLine string) string {
	return fmt.Sprintf(m.info, callLine)
}
func (m mentionFormat) warningFormat(callLine string) string {
	return fmt.Sprintf(m.warning, callLine)
}
func (m mentionFormat) errFormat(callLine string) string {
	return fmt.Sprintf(m.err, callLine)
}
func (m mentionFormat) traceFormat(callLine string, elapsedNano int64, rows int64, sql string) string {
	rs := "-"
	if rows >= 0 {
		rs = fmt.Sprintf("%d", rows)
	}
	return fmt.Sprintf(m.trace, callLine, float64(elapsedNano)/1e6, rs, sql)
}
func (m mentionFormat) traceWarnFormat(callLine string, err error, elapsedNano int64, rows int64, sql string) string {
	rs := "-"
	if rows >= 0 {
		rs = fmt.Sprintf("%d", rows)
	}
	return fmt.Sprintf(m.traceWarn, callLine, err, float64(elapsedNano)/1e6, rs, sql)
}
func (m mentionFormat) traceErrFormat(callLine string, err error, elapsedNano int64, rows int64, sql string) string {
	rs := "-"
	if rows >= 0 {
		rs = fmt.Sprintf("%d", rows)
	}
	return fmt.Sprintf(m.traceErr, callLine, err, float64(elapsedNano)/1e6, rs, sql)
}
